<?php

namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

/**
 * App\Models\User
 *
 * @property int $id
 * @property string $username 用户名
 * @property string $openid openid
 * @property string $email 邮箱
 * @property string $avatar 头像
 * @property string $city 城市
 * @property string $province 省份
 * @property string $country 国家
 * @property int $sex 性别 0：未知、1：男、2：女
 * @property int $integral 积分
 * @property string $balance 余额
 * @property string $money 总金额
 * @property int $agent_one 一级代理IO
 * @property int $agent_two 二级代理ID
 * @property \App\Models\Level $level 会员等级
 * @property string $mobile 手机号
 * @property int $status 状态1正常2锁定
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $login_at
 * @property string $remember_token
 * @property string $nickname 昵称
 * @property int $age 年龄
 * @property int|null $height 身高
 * @property int|null $weight 体重
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @property-read int|null $notifications_count
 * @method static \Database\Factories\UserFactory factory(...$parameters)
 * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User query()
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAge($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAgentOne($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAgentTwo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereBalance($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereCity($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereCountry($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereHeight($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereIntegral($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereLoginAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereMobile($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereNickname($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereOpenid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereProvince($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereRememberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereUsername($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereWeight($value)
 * @mixin \Eloquent
 * @property int|null $is_doctor 医师（1:是，0:否）
 * @property int|null $is_mechanism 机构/商户（1:是，0:否）
 * @method static \Illuminate\Database\Eloquent\Builder|User whereIsDoctor($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereIsMechanism($value)
 */
class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;


    protected $fillable = [
        'id', 'username', 'openid','email', 'avatar', 'city','level',
        'province', 'country', 'sex','integral', 'balance', 'money',
        'agent_one', 'agent_two', 'mobile','status', 'login_at', 'created_at','remember_token','nickname','age'
    ];

    public $timestamps = false;//关闭自动维护
    protected $dates = ['login_at', 'created_at'];

    public function level(){
        return $this->belongsTo('App\Models\Level', 'level', 'id');
    }

    /**
     * 获取列表
     * @param array $params 条件参数
     * @param array $fields 查询的字段
     * @return mixed
     */

    protected function getList($params = [], $fields = ['*']){
        $lists = $this->select($fields)
            ->where(function ($query) use ($params) {
                if(isset($params['kwd']) && $params['kwd']) {
                    $query ->where('username','like','%' . $params['kwd'] . '%');
                }
                if(isset($params['mobile']) && $params['mobile']) {
                    $query ->where('mobile',$params['mobile']);
                }
                if(isset($params['level']) && $params['level']) {
                    $query ->where('level',$params['level']);
                }
                if(isset($params['uid']) && $params['uid']) {
                    $query ->where('id',$params['uid']);
                }
            })->with(['level' => function ($query) {
                $query->select(['name','id']);
            }])->orderBy('id', 'desc')->paginate(config('app.limit'));
        return $lists;
    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }


    public function getJWTCustomClaims()
    {
        return ['role' => 'user'];
    }

    // 小程序建立邀请关系
    public function buildRelationMini($id, $q)
    {
        try {
            $str = 'https://api.panhohealth.cn/api/share/?uid=';
            if (strpos($q, $str) === false) return false;

            $puid = str_replace($str, '', $q);
            if (!is_numeric($puid)) return false;

            $pUser = User::find($puid);
            if (empty($pUser)) return false;

            User::whereId($id)->update([
                'agent_one' => $pUser->id,
                'agent_two' => $pUser->agent_one
            ]);

            return true;
        } catch (\Exception $exception) {
            \Log::error($exception);
            return false;
        }
    }
}
